package cn.loveq.android.widget;

import java.util.List;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import cn.loveq.android.Constants;
import cn.loveq.android.R;
import cn.loveq.android.util.TimeUtils;

import com.waps.AdInfo;
import com.waps.AppConnect;
import com.waps.MiniAdView;
import com.weiny.MmsPlayerActivity;

/**
 * 
 * 
 * 项目名称：loveq4Weibo 类名称：RadioGalleryViewItem 类描述：收音机Gallery的模块 创建人：李伟豪
 * 创建时间：2011-12-5 下午04:35:28
 * 
 * @version
 * 
 */
public class RadioGalleryViewItem extends RelativeLayout implements
		View.OnClickListener, OnSeekBarChangeListener {
	
	private static final String TAG = "RadioGalleryViewItem";
	// private static final String MMSADDRESS =
	// "mms://live.fm993.com.cn/musicfm";
	 private static final String MMSADDRESS = "mms://live.rgd.com.cn/974";
	//private static final String MMSADDRESS = "mms://59.38.110.90/946";
	// private static final String MMSADDRESS = "mms://mslive02.881903.com/cr2";
	// private static final String MMSADDRESS =
	// "mms://218.30.114.31/guangdong_zhujiang_fm974";
	private static final int PROGRESS_CHANGED = 0x001;
	private static final int CURRENT_TIME = 0x002;
	private static final int STARTPROGRAM_TIME = 0x003;
	private static final int PER_SECOND = 1000;
	private int playeredTime = 0;// 已经播放的时间
	private Context mContext;
	private LayoutInflater mInflater;
	private LinearLayout radioMainView;
	private RelativeLayout soundControlBar;// 声音控制面板
	private Handler uiHandler;

	private Button btnMMSWMA;// 开始按钮
	private Button btnStop;// 停止按钮
	//private Button btnSuspend;// 暂停按钮
	private Button btnSound;// 声音按钮
	private TextView currentTime;// 当前时间
	private TextView playedTimer;// 已经播放的时间
	private ImageView radioLogo;// logo
	private SeekBar bar;
	private ProgressBar progress;
	private TextView txtPlayStatus;// 当前状态：
	// private TextView txtStatus;
	private AudioManager mAudioManager;
	private boolean playerStarted;// 播放标识
	private boolean isStop = true;
	public static boolean timerFlag;// 系统时间标识
	private boolean isFirstPlay;// 是第一次播放

	private MyTimerTask myTimerTask;
	private StartPlayedTimerTask startPlayedTimerTask;

	private Thread thread;
	private Thread playedThread;
	private MmsPlayerActivity player;

	private int dfeatures;
	private ImageView favorites;

	public RadioGalleryViewItem(Context context) {
		super(context);
		this.mContext = context;
		// main
		initLayout();
		mAudioManager = (AudioManager) mContext
				.getSystemService(Context.AUDIO_SERVICE);
		initUI();
		enableButtons();

		playeredTime = 0;
		isFirstPlay = false;
		uiHandler = new Handler();

		player = new MmsPlayerActivity();
	
		player.setPlayerHandler(new PlayerHandler() {
			@Override
			public void openPlayerHandler(final int mmsLength) {
				uiHandler.post(new Runnable() {
					public void run() {
						// progress.setProgress(audioBufferSizeMs *
						// progress.getMax() /
						// audioBufferCapacityMs);
						// TODO
						if (mmsLength == 0) {
							btnMMSWMA.setEnabled(false);
							btnStop.setEnabled(true);

							txtPlayStatus.setText(mContext
									.getString(R.string.text_buffering));
							// progress.setProgress(0);
							// progress.setVisibility(View.VISIBLE);

						} else {
							playerStarted = true;
							txtPlayStatus.setText(R.string.text_playing);
							if (playedThread == null) {
								startPlayedTimerTask = new StartPlayedTimerTask();

								playedThread = new Thread(startPlayedTimerTask);
								playedThread.start();

								// final Animation animationIn =
								// AnimationUtils.loadAnimation(mContext,
								// R.anim.logo_fade_in);
								final Animation animationOut = AnimationUtils
										.loadAnimation(mContext,
												R.anim.logo_fade_out);

								radioLogo.startAnimation(animationOut);
								// radioLogo.setAnimation(animationOut);

							}
							//Log.i(TAG, "播放动画");
						}
					}
				});
			}

			@Override
			public void closePlayerHandler() {
				btnStop.setEnabled(false);
				txtPlayStatus.setText("正在关闭...");
				uiHandler.postDelayed(new Runnable() {
					public void run() {
						enableButtons();
						//btnStop.setEnabled(false);
						// txtStatus.setText(R.string.text_stopped);
						if (isStop) {
							txtPlayStatus.setText("停止");
						}
						// progress.setVisibility(View.INVISIBLE);
						if (radioLogo != null) {
							radioLogo.clearAnimation();
						}
						playedThread = null;
						startPlayedTimerTask = null;
						playerStarted = false;
					}
				},3000);
			}
		});

	}

	private void initLayout() {
		this.mInflater = LayoutInflater.from(mContext);
		radioMainView = (LinearLayout) this.mInflater.inflate(
				R.layout.radio_main_layout, null);
		this.setLayoutParams(new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.FILL_PARENT,
				RelativeLayout.LayoutParams.FILL_PARENT));
		this.addView(radioMainView, new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.FILL_PARENT,
				LinearLayout.LayoutParams.FILL_PARENT));
	}

	/**
	 * 初始化UI
	 */
	private void initUI() {
		btnMMSWMA = (Button) radioMainView.findViewById(R.id.radio_btn_start);
		txtPlayStatus = (TextView) radioMainView
				.findViewById(R.id.current_status);
		btnSound = (Button) radioMainView.findViewById(R.id.btn_sound);
		btnStop = (Button) radioMainView.findViewById(R.id.radio_btn_stop);
		//btnSuspend = (Button) radioMainView.findViewById(R.id.radio_btn_suspend);
		currentTime = (TextView) radioMainView.findViewById(R.id.current_time);
		playedTimer = (TextView) radioMainView.findViewById(R.id.played_timer);
		radioLogo = (ImageView) radioMainView.findViewById(R.id.radio_logo);
		bar = (SeekBar) radioMainView.findViewById(R.id.voice_control);
		
		AppConnect.getInstance(mContext).setAdBackColor(Color.TRANSPARENT);//设置迷你广告背景颜色
		favorites = (ImageView) radioMainView.findViewById(R.id.favorites);
		favorites.setOnClickListener(this);
		
	//	LinearLayout miniLayout = (LinearLayout) radioMainView.findViewById(R.id.mini_adLinearLayout);
	//	new MiniAdView(mContext, miniLayout).DisplayAd(10);// 10秒刷新一次
		
		soundControlBar = (RelativeLayout) radioMainView
				.findViewById(R.id.sound_control_bar);

		bar.setProgress(getCurrentVolume());
		btnMMSWMA.setOnClickListener(this);
		btnStop.setOnClickListener(this);
		btnSound.setOnClickListener(soundLintener);
		bar.setOnSeekBarChangeListener(this);
		btnStop.setEnabled(false);
		initTimer();
	}
	
	private void initTimer() {
		myTimerTask = new MyTimerTask();
		timerFlag = true;
		thread = new Thread(myTimerTask);
		thread.start();
		// timer.schedule(myTimerTask, 2000);
	}

	/*
	 * @Override public void playerStarted() { uiHandler.post(new Runnable() {
	 * public void run() { btnMMSWMA.setEnabled(false);
	 * btnStop.setEnabled(true);
	 * 
	 * txtPlayStatus.setText(mContext.getString(R.string.text_buffering)); //
	 * progress.setProgress(0); // progress.setVisibility(View.VISIBLE);
	 * 
	 * playerStarted = true; } }); }
	 */

	/*
	 * @Override public void playerStopped(final int perf) { uiHandler.post(new
	 * Runnable() { public void run() { enableButtons();
	 * btnStop.setEnabled(false); txtBufAudio.setEnabled(true);
	 * txtBufDecode.setEnabled(true); //
	 * txtStatus.setText(R.string.text_stopped); if (isPause) {
	 * txtPlayStatus.setText("暂停,缓存：" + perf + "%"); } else {
	 * txtPlayStatus.setText("停止"); } Log.i(TAG, "-----加载缓存 " + perf + " %"); //
	 * progress.setVisibility(View.INVISIBLE); if (radioLogo != null) {
	 * radioLogo.clearAnimation();
	 * 
	 * } playedThread = null; startPlayedTimerTask = null; playerStarted =
	 * false; } });
	 * 
	 * }
	 */

	/**
	 * 将开始按钮设为可用
	 */
	private void enableButtons() {
		if(isStop)
		 btnMMSWMA.setEnabled(true);
	}

	/*
	 * @Override public void playerPCMFeedBuffer(final boolean isPlaying, final
	 * int audioBufferSizeMs, final int audioBufferCapacityMs) {
	 * uiHandler.post(new Runnable() { public void run() { //
	 * progress.setProgress(audioBufferSizeMs * progress.getMax() / //
	 * audioBufferCapacityMs); // TODO if (isPlaying) {
	 * txtPlayStatus.setText(R.string.text_playing); if (playedThread == null) {
	 * startPlayedTimerTask = new StartPlayedTimerTask();
	 * 
	 * playedThread = new Thread(startPlayedTimerTask); playedThread.start();
	 * 
	 * // final Animation animationIn = AnimationUtils.loadAnimation(mContext,
	 * R.anim.logo_fade_in); final Animation animationOut =
	 * AnimationUtils.loadAnimation(mContext, R.anim.logo_fade_out);
	 * 
	 * radioLogo.startAnimation(animationOut); //
	 * radioLogo.setAnimation(animationOut);
	 * 
	 * } Log.i(TAG, "播放动画"); } } }); }
	 */
	/*
	 * @Override public void playerException(final Throwable t) {
	 * uiHandler.post(new Runnable() { public void run() { new
	 * AlertDialog.Builder
	 * (mContext).setTitle(R.string.text_exception).setMessage
	 * (t.toString()).setNeutralButton(R.string.button_close, new
	 * DialogInterface.OnClickListener() { public void onClick(DialogInterface
	 * dialog, int id) { dialog.cancel(); } }).show();
	 * 
	 * // txtStatus.setText(R.string.text_stopped);
	 * 
	 * if (playerStarted) playerStopped(0); } });
	 * 
	 * }
	 */

	@Override
	public void onClick(View v) {
		try {
			switch (v.getId()) {
			case R.id.radio_btn_start:
				int state = checkNetworkInfo();
				if (state == Constants.ConnectType.CONNECT_TYPE_WIFI) {
					isStop = false;
					start();
					btnMMSWMA.setEnabled(false);
					// txtStatus.setText(R.string.text_using_MMSWMA);

				} else if (state == Constants.ConnectType.CONNECT_TYPE_VPN) {
					if (!isFirstPlay) {
						showNetworkDialog();
					} else {
						isStop = false;
						start();
						btnMMSWMA.setEnabled(false);
					}
				} else if (state == Constants.ConnectType.CONNECT_TYPE_UNKNOW) {
					showErrorNetworkDialog();
				}

				break;
	/*		case R.id.radio_btn_suspend:
				isPause = true;
				pause();
				break;*/
			case R.id.radio_btn_stop:
				isStop = true;
				stop();
				break;
			case R.id.favorites:
				Toast.makeText(mContext, "更多应用", Toast.LENGTH_SHORT).show();
				AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
				View view = getListView();
				if(view != null){
					builder.setView(getListView());
				}else{
					builder.setMessage("未获取到数据");
				}
		    	builder.create().show();
				
				break;
			}
		} catch (Exception e) {
			Log.e("AACPlayerActivity", "exc", e);
		}
	}

	/**
	 * 开始
	 */
	public void start() {
		stop();
		if (player != null) {
			player.openPlayer(MMSADDRESS);

		}
	}

	public boolean isStoped(){
		return !isStop;
	}
	
	/**
	 * 停止
	 */
	public void stop() {
		if (player != null) {
			player.closePlayer();
		}
	}

	private int getInt(EditText et) {
		return Integer.parseInt(et.getText().toString());
	}

	/**
	 * 声音监听器
	 */
	Button.OnClickListener soundLintener = new Button.OnClickListener() {

		@Override
		public void onClick(View v) {
			if (soundControlBar.getVisibility() == View.INVISIBLE) {
				soundControlBar.setVisibility(View.VISIBLE);
			} else {
				soundControlBar.setVisibility(View.INVISIBLE);
			}
		}

	};

/*	*//**
	 * 音乐控制,seekbar 进程改变
	 *//*
	@Override
	public void onProgressChanged(VerticalSeekBar VerticalSeekBar,
			int progress, boolean fromUser) {
		// Toast.makeText(mContext, "当前值：" + progress,
		// Toast.LENGTH_SHORT).show();
		Message msg = new Message();
		msg.arg1 = progress;
		msg.what = PROGRESS_CHANGED;
		mHandler.sendMessageDelayed(msg, 100);
	}

	*//**
	 * 音乐控制,seekbar 拖动中
	 *//*
	@Override
	public void onStartTrackingTouch(VerticalSeekBar verticalSeekBar) {
		Toast.makeText(mContext, "拖动中", Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onStopTrackingTouch(VerticalSeekBar VerticalSeekBar) {
	}*/
	
	/**
	 * 设置音量
	 */
	private void setVolume(int currentProgress) {
		int maxVolume = mAudioManager
				.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		bar.setMax(maxVolume);
		// int currentVolume =
		// mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
		// bar.setProgress(currentVolume);
		mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
				currentProgress * 100 / maxVolume, 0);
		Log.i(TAG, "currentVolume" + currentProgress * 100 / maxVolume);
	}

	/**
	 * 获取当初音量
	 */
	private int getCurrentVolume() {
		return mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC) * 100 / 100;
	}

	/**
	 * 检查网络状态
	 */
	private int checkNetworkInfo() {
		ConnectivityManager conMan = (ConnectivityManager) mContext
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		// mobile 3G Data Network
		State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
				.getState();
		// wifi
		State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
				.getState();

		// 如果3G网络和wifi网络都未连接，且不是处于正在连接状态 则进入Network Setting界面 由用户配置网络连接
		if (mobile == State.CONNECTED || mobile == State.CONNECTING)
			return Constants.ConnectType.CONNECT_TYPE_VPN;
		if (wifi == State.CONNECTED || wifi == State.CONNECTING)
			return Constants.ConnectType.CONNECT_TYPE_WIFI;
		return Constants.ConnectType.CONNECT_TYPE_UNKNOW;

	}

	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case PROGRESS_CHANGED:
				try {
					// if (playerStarted) {
					setVolume(msg.arg1);
					// }
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			case CURRENT_TIME:
				// currentTime.setText(TimeUtils.getFormateCreatedDate());
				currentTime.setText(TimeUtils.getNowTime());
				break;
			case STARTPROGRAM_TIME:
				// TODO
				playeredTime++;
				playedTimer.setText(TimeUtils.cal(playeredTime));
				if(playeredTime % 900 == 0)
					System.gc();
				break;
			default:
				break;
			}

			super.handleMessage(msg);

		}

	};

	
	
	/**
	 * 显示网络对话框
	 */
	private void showNetworkDialog() {
		Builder builder = new AlertDialog.Builder(mContext);
		builder.setTitle(mContext.getText(R.string.network_info_title));
		builder.setMessage(mContext.getText(R.string.network_info_message));
		builder.setIcon(R.drawable.warn);
		builder.setPositiveButton(R.string.go_on,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						isFirstPlay = true;
						dialog.dismiss();
					}
				});
		builder.setNegativeButton(R.string.exit,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialoginterface, int i) {
						System.exit(0);
					}
				});

		builder.show();
	}

	/**
	 * 显示错误网络对话框
	 */
	private void showErrorNetworkDialog() {
		Builder builder = new AlertDialog.Builder(mContext);
		builder.setTitle(mContext.getText(R.string.set_network));
		builder.setMessage(mContext.getText(R.string.network_info_error));
		builder.setIcon(R.drawable.warn);
		builder.setPositiveButton(R.string.set_network,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						mContext.startActivity(new Intent(
								Settings.ACTION_WIRELESS_SETTINGS));// 进入无线网络配置界面
					}
				});
		builder.setNegativeButton(R.string.exit,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialoginterface, int i) {
						System.exit(0);
					}
				});

		builder.show();
	}

	class StartPlayedTimerTask implements Runnable {

		@Override
		public void run() {
			while (playerStarted) {

				Message msg = new Message();
				msg.what = STARTPROGRAM_TIME;
				mHandler.sendMessage(msg);
				Log.i(TAG, "StartPlayedTimerTask.....");
				try {
					Thread.sleep(PER_SECOND);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}

	
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if(bar != null && soundControlBar !=null && soundControlBar.getVisibility() != View.INVISIBLE){
			float x = event.getX();
			float y = event.getY();
			Rect rect = new Rect();
			bar.getGlobalVisibleRect(rect);
			if(!rect.contains((int)x, (int)y)){
				soundControlBar.setVisibility(View.INVISIBLE);
			}
		}
		
		return super.onTouchEvent(event);
	}

	class MyTimerTask implements Runnable {
		@Override
		public void run() {
			while (timerFlag) {
				Message msg = new Message();
				msg.what = CURRENT_TIME;
				mHandler.sendMessage(msg);
				// Log.i(TAG, "timer.....");
				try {
					Thread.sleep(PER_SECOND);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromUser) {
		// Toast.makeText(mContext, "当前值：" + progress,
				// Toast.LENGTH_SHORT).show();
				Log.i("vita", "progress = " + progress);
				Message msg = new Message();
				msg.arg1 = progress;
				msg.what = PROGRESS_CHANGED;
				mHandler.sendMessageDelayed(msg, 100);		
	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		//Toast.makeText(mContext, "拖动中", Toast.LENGTH_SHORT).show();		
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		
	}

	
	 /**
     * 获取适配后的ListView
     * @return ListView实例
     */
    private View getListView(){
    	ListView listView = new ListView(mContext);
    	@SuppressWarnings("unchecked")
		final List<AdInfo> list = AppConnect.getInstance(mContext).getAdInfoList();
    	if(list != null && list.size() > 0){
	    	listView.setAdapter(new AdAdapter(mContext, list));
	    	listView.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					AppConnect.getInstance(mContext).clickAd(list.get(position).getAdId());
				}
			});
	    	return listView;
    	}else{
    		return null;
    	}
    	
    }
}
